package com.nelson.encrypt.task;

import com.nelson.encrypt.bean.PluginParams;
import com.nelson.encrypt.utils.LogUtils;

import org.gradle.api.Action;
import org.gradle.api.DefaultTask;
import org.gradle.api.tasks.TaskAction;
import org.gradle.process.ExecSpec;
import java.io.File;
import javax.inject.Inject;

/**
 * <pre>
 *   @author :   李磊
 *   time    :   2021/10/10
 *   des     :
 * </pre>
 */
public class EncryptTask extends DefaultTask {
    private File mOutputFile;
    private PluginParams mPluginParams;

    @Inject
    public EncryptTask(File outputFile, PluginParams pluginParams) {
        setGroup("Encrypt");
        mOutputFile = outputFile;
        mPluginParams = pluginParams;
    }

    @TaskAction
    public void encrypt() {
        // 当该任务被执行时，会调用该方法
        LogUtils.i("Encrypt Start");

        // 执行加固 ---------------

        // 登录
        getProject().exec(new Action<ExecSpec>() {
            @Override
            public void execute(ExecSpec execSpec) {
                ExecSpec commandLine = execSpec.commandLine(
                        "java",
                        "-jar",
                        mPluginParams.getToolPath(),
                        "-login",
                        mPluginParams.getUserName(),
                        mPluginParams.getPassword()
                );


            }
        });

        // 签名
        getProject().exec(new Action<ExecSpec>() {
            @Override
            public void execute(ExecSpec execSpec) {
                // 是否配置签名
                String keyStorePath = mPluginParams.getKeyStorePath();
                if (keyStorePath == null || keyStorePath.isEmpty()) {
                    return;
                }
                execSpec.commandLine(
                        "java",
                        "-jar",
                        mPluginParams.getToolPath(),
                        "-importsign ",
                        mPluginParams.getKeyStorePath(),
                        mPluginParams.getKeyStorePwd(),
                        mPluginParams.getKeyStoreKeyAlias(),
                        mPluginParams.getKeyStoreKeyAliasPwd()
                );
            }
        });

        // 加固
        getProject().exec(new Action<ExecSpec>() {
            @Override
            public void execute(ExecSpec execSpec) {
                // 是否配置签名
                String keyStorePath = mPluginParams.getKeyStorePath();
                if (keyStorePath == null || keyStorePath.isEmpty()) {
                    return;
                }
                execSpec.commandLine(
                        "java",
                        "-jar",
                        mPluginParams.getToolPath(),
                        "-jiagu ",
                        mOutputFile.getAbsolutePath(),
                        mOutputFile.getParent(),
                        "-autosign"
                );
            }
        });

        // 执行加固 ---------------
    }
}